"""应用配置管理"""
import os
from typing import Optional
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()


class Settings:
    """应用配置类"""
    
    # LegalBERT 模型配置
    LEGALBERT_MODEL_NAME: str = os.getenv(
        "LEGALBERT_MODEL_NAME", 
        "nlpaueb/legal-bert-base-uncased"
    )
    LEGALBERT_DEVICE: str = os.getenv("LEGALBERT_DEVICE", "cpu")
    LEGALBERT_MAX_LENGTH: int = int(os.getenv("LEGALBERT_MAX_LENGTH", "512"))
    
    # API 配置
    API_HOST: str = os.getenv("API_HOST", "0.0.0.0")
    API_PORT: int = int(os.getenv("API_PORT", "8000"))
    API_TITLE: str = os.getenv("API_TITLE", "LegalBERT AI Service")
    API_VERSION: str = os.getenv("API_VERSION", "1.0.0")
    
    # 日志配置
    LOG_LEVEL: str = os.getenv("LOG_LEVEL", "INFO")
    
    # PostgreSQL 配置（从环境变量读取，如果没有则使用默认值）
    POSTGRES_HOST: str = os.getenv("POSTGRES_HOST", "localhost")
    POSTGRES_PORT: int = int(os.getenv("POSTGRES_PORT", "5432"))
    POSTGRES_DB: str = os.getenv("POSTGRES_DB", "ailawer")
    POSTGRES_USER: str = os.getenv("POSTGRES_USER", "ailawer")
    POSTGRES_PASSWORD: str = os.getenv("POSTGRES_PASSWORD", "password")
    
    # 搜索配置
    SEARCH_API_KEY: Optional[str] = os.getenv("SEARCH_API_KEY")  # 搜索引擎API密钥（可选）
    CRAWL_INTERVAL_HOURS: int = int(os.getenv("CRAWL_INTERVAL_HOURS", "24"))  # 爬取间隔（小时）
    MAX_SEARCH_RESULTS: int = int(os.getenv("MAX_SEARCH_RESULTS", "100"))  # 最大搜索结果数
    
    @property
    def device(self) -> str:
        """获取设备配置，如果指定了 cuda 但不可用则回退到 cpu"""
        if self.LEGALBERT_DEVICE == "cuda":
            try:
                import torch
                if torch.cuda.is_available():
                    return "cuda"
            except ImportError:
                pass
        return "cpu"


# 全局配置实例
settings = Settings()

